<?php

namespace App\Library\KfHttp;

use App\Kuafu\Base\Service\BaseService;
use App\Library\SnowFlake\SnowFlake;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
use Illuminate\Support\Facades\Log;

/**
 * 调用kf的curl方法
 */
class BaseKfCurl extends BaseService
{
    protected $header;
    protected $domain;
    protected $timeOut;

    protected function __construct()
    {
        parent::__construct();
        $this->header = [
            'internal-key'     => 'tiger',
            'internal-token'   => config('InternalAPI.tokens.tiger'),
            'X-Requested-With' => 'XMLHttpRequest', // 传这个头，报错结果是json，而不是html
        ];

//        $this->domain  = env('RMS_DOMAIN');
        $this->timeOut = 10;
    }

    public static function getIns(): self
    {
        return new static;
    }

    public function setHeader(array $header): self
    {
        $this->header = array_merge($this->header, $header);
        return $this;
    }

    public function setDomain(string $domain): self
    {
        $this->domain = $domain;
        return $this;
    }

    public function setTimeOut(int $timeOut): self
    {
        $this->timeOut = $timeOut;
        return $this;
    }

    /**
     * 发送请求
     * @param string $path api/internal/xxxx
     * @param array $data
     * @param string $method GET/POST/PUT/PATCH/DELETE
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function do(string $path, array $data, string $method = 'POST'): array
    {
        $url = $this->domain . $path;

        $uuid = SnowFlake::nextIdCache();

        $method = strtoupper($method);
        if ($method == 'GET') {
            $bodyType = RequestOptions::QUERY;
        } else {
            $bodyType = RequestOptions::JSON;
            Log::info("Kfhttp Curldo uuid:{$uuid} in: {$this->domain}/{$path} " . json_encode($data, JSON_UNESCAPED_UNICODE));
        }
        $response = (new Client([
            'timeout'     => $this->timeOut,
            'http_errors' => false, // 不会抛异常
        ]))->request($method, $url, [
            'headers' => $this->header,
            $bodyType => $data,
        ]);
        $res = json_decode($response->getBody()->getContents(), true) ?? [];

        // 操作类才记录返回值
        if ($method != 'GET') {
            Log::info("Kfhttp uuid:{$uuid} out:" . json_encode($res, JSON_UNESCAPED_UNICODE));
        }

        if (isset($res['code']) && ($res['code'] == 200 || $res['code'] == 0)) {
            return BaseService::returnData(1, '', $res['data'] ?? []);
        }

        $msg = $res['msg'] ?? '';
        if (!$msg) {
            $msg = $res['message'] ?? '';
        }

        if (!$msg) {
            $msg = "报错信息为空";
        }

        return BaseService::returnData(0, $msg);
    }
}
